import axios from 'axios'
import type { ExaminationResponse, ExamDetailResponse, CreateExamParams } from './type'

const BASE_URL = ' http://121.89.213.194:3001';

// 获取考试记录列表
export const getExaminationApi = async (page = 1, pageSize = 10) => {
  return axios.get<ExaminationResponse>(`/exam/list`, {
    params: { 
      page,
      pageSize
    }
  })
}

// 获取考试详情
export const getExamDetailApi = async (examId: string) => {
  return axios.get<ExamDetailResponse>(`/examination/detail`, {
    params: { id: examId }
  })
}
// 获取考试列表(支持多条件查询)
export const getExaminationsApi = (params: {
  page?: number
  pagesize?: number
  name?: string
  classify?: string 
  status?: number
  startTime?: string
  endTime?: string
  creator?: string
} = {}) => {
  // 设置默认分页参数
  const requestParams = {
    page: 1,
    pagesize: 1000,
    ...params
  }
  
  return axios.get<ExaminationResponse>('/examination/list', {
    params: requestParams
  })
}

// 创建考试场次
export const createExaminationApi = async (params: CreateExamParams) => {
  // 参数转换和映射
  const name = params.name || (params as any).examName;
  const examId = params.examId || params.exam || (params as any).selectedPaper?._id;
  
  // 确保group格式为字符串ID
  const group = String(params.group || params.class || (params as any).class || '');
  if (!group) throw new Error('group参数不能为空');
  
  // 处理examiners参数
  const proctor = params.examiner || params.proctor || (params as any).proctor;
  const examiners = [];
  
  if (proctor) {
    if (Array.isArray(proctor)) {
      examiners.push(...proctor.map(p => String(p)));
    } else {
      examiners.push(String(proctor));
    }
    
    if (!examiners.every(isValidId)) {
      throw new Error('examiners参数包含无效的ID格式，请确保传递的是有效的ObjectId');
    }
  }
  
  // 确保classify是有效的科目ID
  const subject = (params as any).subject;
  const classify = String(params.classify || subject || (params as any).classify || '');
  
  if (!classify) throw new Error('classify参数不能为空');
  if (!isValidId(classify)) throw new Error('classify参数必须是有效的科目ID格式');
  


  console.log('参数格式验证:', {
    name: typeof name,
    classify: typeof classify,
    examId: typeof examId,
    group: typeof group,
    examiners: typeof examiners
  });
  
  console.log('原始参数:', params);
  console.log('转换后参数:', {
    name,
    classify,
    examId, 
    group,
    examiners,
    startTime: params.startTime,
    endTime: params.endTime
  });

  // 验证必填参数
  const missingFields = [];
  if (!name) missingFields.push('name');
  if (!classify) missingFields.push('classify');
  if (!examId) missingFields.push('examId');
  if (!group) missingFields.push('group');
  if (!examiners.length) missingFields.push('examiners');
  if (!params.startTime) missingFields.push('startTime');
  if (!params.endTime) missingFields.push('endTime');

  if (missingFields.length > 0) {
    throw new Error(`缺少必填参数: ${missingFields.join(', ')}`);
  }

  // 时间格式转换
  const formatTime = (time: string | number | unknown) => {
    if (typeof time === 'number') {
      return new Date(time).toISOString();
    }
    if (typeof time === 'string') {
      return time;
    }
    // 处理moment对象
    if (time && typeof time === 'object' && 'valueOf' in time) {
      const timestamp = (time as {valueOf: () => number}).valueOf();
      return new Date(timestamp).toISOString();
    }
    throw new Error('无效的时间格式');
  };

  // 设置默认值
  const defaultSettings = {
    allowLate: false,
    allowEarly: false,
    allowReview: true,
    allowDiscuss: false,
    ...(params.settings || {})
  };

  const requestParams = {
    name,
    classify,
    examId,
    group,
    examiner: examiners[0], // 保持向后兼容
    examiners,              // 新格式
    startTime: formatTime(params.startTime),
    endTime: formatTime(params.endTime),
    settings: defaultSettings,
    ...(params.creator ? { creator: params.creator } : {})
  };

  return axios.post(`/examination/create`, requestParams);
}

// 更新考试
export const updateExamApi = async (params: CreateExamParams) => {
  return axios.post<ExaminationResponse>(`/exam/update`, params)
}

// 删除考试记录
export const deleteExamsApi = async (ids: string[]) => {
  return axios.post(`/exam/remove`, { ids })
}
// 删除单个考试记录
export const deleteExamApi = async (id: string) => {
  return axios.post(`/examination/remove`, { id })
}



